#  Copyright (c) 2021- ~, XIWANG
#  
#  OLSR simulation analyze .tr
#  Used in awk
#  Clone from https://gitee.com/WangXi_Chn/olsr_-analysis.git
#  Note in https://www.yuque.com/wangxi_chn
#  
#  Change Logs:
#  Date             Author      Notes			Mail
#  2021-2-21        XiWang      first version	WangXi_Chn@foxmail.com

BEGIN {
    count_cbr_send = 0; #发送的CBR封包的数目
    count_cbr_recv = 0; #接收的CBR封包的数目
    count_cbr_nroute = 0; #因路由中断的丢包数目

    highest_packet_id = 0;#最大包ID

    count_olsr_send = 0; #发送的控制消息
    size_olsr = 0; #总olsr路由协议开销
}

{
    event = $1;
    time = $2;
    node_nb = $3;
    node_nb=substr(node_nb,2,1);
    trace_type = $4;
    flag = $5;
    packet_id = $6
    pkt_type = $7;
    pkt_size = $8;

    if (event== "s" && trace_type == "AGT" && pkt_type== "cbr")
        count_cbr_send++;
    if (event== "r" && trace_type == "AGT" && pkt_type== "cbr")
        count_cbr_recv++;
    if (event== "D" && flag == "NRTE" && pkt_type== "cbr")
        count_cbr_nroute++;

    if ( pkt_type== "cbr" ) 
    {
	    if ( packet_id > highest_packet_id )
		    highest_packet_id = packet_id;
	    if (event == "s" )  
		    start_time[packet_id] = time;
	    if (event == "r" )
	    {
		    end_time[packet_id] = time;
	    }else{
		    end_time[packet_id] = -1;
		}
    }

    if (pkt_type== "OLSR" && event == "s") 
    {
	    count_olsr_send++;
	    size_olsr = size_olsr + pkt_size;
    }
}

END {
    noroute_rate = 0; #因路由中断导致的丢包率
    noroute_rate = count_cbr_nroute/count_cbr_send; 
    # noroute_rate = count_cbr_recv/count_cbr_send;
    

    i = 0; #正常接收的cbr包数
    for ( packet_id = 0; packet_id <= highest_packet_id; packet_id++ )
    {
        start = start_time[packet_id];
        end = end_time[packet_id];
        if ( start <= end )
		{	
			packet_delay = end - start;
			delaysum += packet_delay;
			i++;
		}
   	}

    etedelay=0; #端到端平均时延
    etedelay = delaysum / i;
    
    control_rate = 0; # 控制开销
    control_rate = count_olsr_send/count_cbr_send;
    printf("%f %f %f\n",noroute_rate,etedelay,control_rate);
}

#/************************ (C) COPYRIGHT 2021 XIWANG**************END OF FILE****/
